package com.glsc.ngateway.opmanage.service.archive;


import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.*;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.document.DocumentInfo;
import com.glsc.ngateway.common.base.dto.opmanage.report.archive.ArchiveClientOrgDto;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.archive.*;
import com.glsc.ngateway.opmanage.enums.ArchiveEnum;
import com.glsc.ngateway.opmanage.dto.ArchiveFileDto;
import com.glsc.ngateway.opmanage.dto.OaFileDto;
import com.glsc.ngateway.opmanage.dto.TreeDto;
import com.glsc.ngateway.opmanage.enums.TaskTypeUrlEnum;
import com.glsc.ngateway.opmanage.event.vo.TaskInfoEvent;
import com.glsc.ngateway.opmanage.service.document.DocumentService;
import com.glsc.ngateway.opmanage.service.feign.GatewayFeignService;
import com.glsc.ngateway.opmanage.utils.RequestTool;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArchiveService {

    @Resource
    private ArchiveClientDirDocRepository clientDirDocRepository;

    @Resource
    private ArchiveClientRepository clientRepository;

    @Resource
    private ArchiveDirClientRepository dirClientRepository;

    @Resource
    private ArchiveDirTemplateRepository dirTemplateRepository;

    @Resource
    private ArchiveDocumentRepository archiveDocumentRepository;

    @Resource
    private ArchiveFileInfoRepository fileInfoRepository;

    @Resource
    private DocumentService documentService;

    @Resource
    private GatewayFeignService gatewayFeignService;

    @Resource
    private RequestTool requestTool;

    @Resource
    private ApplicationContext applicationContext;


    /**
     * 分页条件查询客户信息
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<ArchiveClient> findClientPage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<ArchiveClient> page = clientRepository.findAll(SpecificationUtil.buildSpecification(param, ArchiveClient.class), pageable);

        if (Objects.nonNull(page) && CollectionUtils.isNotEmpty(page.getContent())) {
            for (ArchiveClient client : page.getContent()) {
                List<ArchiveClientDirDoc> docs = listNoConnectFileByClientId(client.getClientId());
                client.setWaitDealFileCount(CollectionUtils.isNotEmpty(docs) ? docs.size() : null);
            }
        }

        return page;
    }

    /**
     * 查询机构客户的客户信息汇总表
     *
     * @param partyName
     * @param partyOrganCode
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Page<ArchiveClientOrgDto> findOrgClientPage(String partyName, String partyOrganCode, Integer pageNo, Integer pageSize) {

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        //只查询机构客户
        Page<Map<String, Object>> page = clientRepository.findOrgClientPage(partyName, partyOrganCode, pageable);
        if (CollectionUtils.isEmpty(page.getContent())) {
            return Page.empty();
        }

        List<ArchiveClientOrgDto> list = Lists.newArrayList();
        for (Map<String, Object> map : page.getContent()) {
            ArchiveClientOrgDto archiveClientOrgDto = new ArchiveClientOrgDto();
            archiveClientOrgDto.setId(Integer.parseInt(String.valueOf(map.get("id"))));
            archiveClientOrgDto.setPartyName(String.valueOf(map.get("party_name")));
            archiveClientOrgDto.setPartyOrganCode("");
            if (Objects.nonNull(map.get("party_organ_code"))) {
                archiveClientOrgDto.setPartyOrganCode(String.valueOf(map.get("party_organ_code")));
            }
            archiveClientOrgDto.setCnt(0);
            if (Objects.nonNull(map.get("cnt"))) {
                archiveClientOrgDto.setCnt(Integer.parseInt(String.valueOf(map.get("cnt"))));
            }
            List<ArchiveClient> clientList = findClientsByPartyId(Integer.parseInt(String.valueOf(map.get("id"))), null);
            if (CollectionUtils.isNotEmpty(clientList)) {
                //按照先机构后产品的顺序排序
                clientList = clientList.stream().sorted(Comparator.comparing(ArchiveClient::getClientType).reversed()).collect(Collectors.toList());
                archiveClientOrgDto.setClientId(StringUtils.join(clientList.stream().map(ArchiveClient::getClientId).collect(Collectors.toList()), ","));
                archiveClientOrgDto.setClientName(StringUtils.join(clientList.stream().map(ArchiveClient::getClientName).collect(Collectors.toList()), ","));
            }
            list.add(archiveClientOrgDto);
        }

        return new PageImpl<ArchiveClientOrgDto>(list, page.getPageable(), page.getTotalPages());
    }


    /**
     * 根据交易对手方信息查找所有的客户信息
     *
     * @param partyId
     * @return
     */
    public List<ArchiveClient> findClientsByPartyId(Integer partyId, String clientType) {
        if (Objects.isNull(partyId)) {
            return null;
        }
        ArchiveClient condition = ArchiveClient.builder().partyId(partyId).build();
        if (StringUtils.isNotBlank(clientType)) {
            condition.setClientType(clientType);
        }
        List<ArchiveClient> list = clientRepository.findAll(Example.of(condition));
        return list;
    }

    /**
     * 根据客户id查询客户信息
     *
     * @param clientId
     * @return
     */
    public ArchiveClient findClientById(String clientId) {
        if (StringUtils.isBlank(clientId)) {
            return null;
        }
        List<ArchiveClient> clientList = clientRepository.findAll(Example.of(ArchiveClient.builder().clientId(clientId).build()));

        if (CollectionUtils.isEmpty(clientList)) {
            return null;
        }
        return clientList.get(0);
    }

    /**
     * 根据客户id查询客户目录
     *
     * @param clientId
     * @return
     */
    public List<ArchiveDirClient> findArchiveDirClientByClientId(String clientId) {
        if (StringUtils.isBlank(clientId)) {
            return null;
        }
        return dirClientRepository.findAll(Example.of(ArchiveDirClient.builder().clientId(clientId).build()));
    }

    /**
     * 返回树形结构客户目录信息
     *
     * @param clientId
     * @return
     */
    public TreeDto buildChildrenArchiveDirClientByClientId(String clientId) {
        List<ArchiveDirClient> archiveDirClientList = findArchiveDirClientByClientId(clientId);
        if (CollectionUtils.isNotEmpty(archiveDirClientList)) {
            List<TreeDto> treeDtoList = Lists.newArrayList();
            for (ArchiveDirClient archiveDirClient : archiveDirClientList) {
                treeDtoList.add(TreeDto.builder().title(archiveDirClient.getClientDirName()).key(archiveDirClient.getClientDirId())
                        .clientParentDirId(archiveDirClient.getClientParentDirId()).saveFileFlag(archiveDirClient.getSaveFileFlag()).build());
            }

            TreeDto res = null;
            for (TreeDto dirClient : treeDtoList) {
                List<TreeDto> children = treeDtoList.stream().filter(e -> dirClient.getKey().equals(e.getClientParentDirId())).collect(Collectors.toList());
                dirClient.setChildren(children);
            }
            for (TreeDto dirClient : treeDtoList) {
                if (Objects.isNull(dirClient.getClientParentDirId())) {
                    res = dirClient;
                    break;
                }
            }

            return res;
        }
        return null;
    }

    /**
     * 根据客户目录id获取所有的文件信息
     *
     * @param clientDirId
     * @return
     */
    public List<ArchiveFileInfo> findArchiveFileInfoByClientDirId(Integer clientDirId) {
        if (Objects.isNull(clientDirId)) {
            return Lists.newArrayList();
        }
        Optional<ArchiveDirClient> optional = dirClientRepository.findById(clientDirId);
        if (!optional.isPresent()) {
            return Lists.newArrayList();
        }
        ArchiveDirClient archiveDirClient = optional.get();

        List<ArchiveClientDirDoc> clientDirDocList = clientDirDocRepository.findAll(Example.of(ArchiveClientDirDoc.builder()
                .clientDirId(archiveDirClient.getClientDirId()).clientId(archiveDirClient.getClientId()).build()));
        if (CollectionUtils.isEmpty(clientDirDocList)) {
            return Lists.newArrayList();
        }

        List<Integer> docIdList = clientDirDocList.stream().map(ArchiveClientDirDoc::getDocId).collect(Collectors.toList());
        Map<String, Object> documentParam = new HashMap<>();
        documentParam.put("IN_docId", StringUtils.join(docIdList, ","));
        List<ArchiveDocument> archiveDocumentList = findDocumentByCondition(documentParam);
        if (CollectionUtils.isEmpty(archiveDocumentList)) {
            return Lists.newArrayList();
        }
        List<Integer> fileIdList = archiveDocumentList.stream().filter(e -> Objects.nonNull(e.getFileId())).map(ArchiveDocument::getFileId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(fileIdList)) {
            return Lists.newArrayList();
        }

        Map<String, Object> fileParam = new HashMap<>();
        fileParam.put("IN_fileId", StringUtils.join(fileIdList, ","));
        List<ArchiveFileInfo> fileInfoList = findFileByCondition(fileParam);
        if (CollectionUtils.isEmpty(fileInfoList)) {
            return Lists.newArrayList();
        }
        return fileInfoList;
    }

    /**
     * 根据客户id查询未关联目录文件
     *
     * @param clientId
     * @return
     */
    public List<ArchiveFileInfo> findNoRelatedArchiveFileInfoByClientId(String clientId) {
        if (Objects.isNull(clientId)) {
            return Lists.newArrayList();
        }

        List<ArchiveClientDirDoc> clientDirDocList = clientDirDocRepository.findAll(Example.of(ArchiveClientDirDoc.builder()
                .clientId(clientId).build()));
        if (CollectionUtils.isEmpty(clientDirDocList)) {
            return Lists.newArrayList();
        }
        List<Integer> docIdList = clientDirDocList.stream().filter(e -> Objects.isNull(e.getClientDirId())).map(ArchiveClientDirDoc::getDocId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(docIdList)) {
            return Lists.newArrayList();
        }

        Map<String, Object> documentParam = new HashMap<>();
        documentParam.put("IN_docId", StringUtils.join(docIdList, ","));
        List<ArchiveDocument> archiveDocumentList = findDocumentByCondition(documentParam);
        if (CollectionUtils.isEmpty(archiveDocumentList)) {
            return Lists.newArrayList();
        }
        List<Integer> fileIdList = archiveDocumentList.stream().filter(e -> Objects.nonNull(e.getFileId())).map(ArchiveDocument::getFileId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(fileIdList)) {
            return Lists.newArrayList();
        }
        Map<String, Object> fileParam = new HashMap<>();
        fileIdList = fileIdList.stream().filter(e -> Objects.nonNull(e)).collect(Collectors.toList());
        fileParam.put("IN_fileId", StringUtils.join(fileIdList, ","));

        List<ArchiveFileInfo> fileInfoList = findFileByCondition(fileParam);
        if (CollectionUtils.isEmpty(fileInfoList)) {
            return Lists.newArrayList();
        }
        return fileInfoList;
    }

    /**
     * 新建客户文件-文档关系
     */
    @Transactional
    public void saveClientFile(ArchiveFileDto dto) {
        Assert.notNull(dto.getFileDocId(), "文件id不可为空");

        ArchiveClientDirDoc clientDirDoc = null;
        ArchiveDocument archiveDocument = null;
        ArchiveFileInfo archiveFileInfo = null;

        User opUser = requestTool.getUserFromRequest();

        //检查这一级目录是否可以保存文件信息
        Optional<ArchiveDirClient> clientOptional = dirClientRepository.findById(dto.getClientDirId());
        Assert.isTrue(clientOptional.isPresent(), "关联目录信息不存在");

        ArchiveDirClient dirClient = clientOptional.get();
        Assert.isTrue(1 == dirClient.getSaveFileFlag(), "此目录不允许关联文件信息");

        if (Objects.nonNull(dto.getDocId())) {
            //更新
            Optional<ArchiveClientDirDoc> optional = clientDirDocRepository.findById(dto.getDocId());
            if (optional.isPresent()) {
                clientDirDoc = optional.get();
            }
            Assert.notNull(clientDirDoc, "未查询到指定的doc信息");

            Optional<ArchiveDocument> documentOptional = archiveDocumentRepository.findById(clientDirDoc.getDocId());
            if (documentOptional.isPresent()) {
                archiveDocument = documentOptional.get();
            }
            Assert.notNull(archiveDocument, "未查询到指定的document信息");

            Optional<ArchiveFileInfo> fileInfoOptional = fileInfoRepository.findById(archiveDocument.getFileId());
            if (fileInfoOptional.isPresent()) {
                archiveFileInfo = fileInfoOptional.get();
            }
        } else {
            //新增
            clientDirDoc = new ArchiveClientDirDoc();
            clientDirDoc.setClientDirId(dto.getClientDirId());
            clientDirDoc.setClientId(dto.getClientId());
            clientDirDoc = clientDirDocRepository.save(clientDirDoc);

            archiveDocument = new ArchiveDocument();
            archiveDocument.setDocId(clientDirDoc.getDocId());

        }

        //新增或者更新时
        if (Objects.isNull(archiveFileInfo) || (Objects.nonNull(archiveFileInfo) && Objects.nonNull(dto.getFileDocId()) && dto.getFileDocId() != archiveFileInfo.getDocId())) {
            DocumentInfo fileDocument = documentService.findById(dto.getFileDocId());
            Assert.notNull(fileDocument, "未查询到上传的文件信息");
            archiveFileInfo = new ArchiveFileInfo();
            archiveFileInfo.setFileName(fileDocument.getFileName());
            archiveFileInfo.setFilePath(fileDocument.getFilePath());
            archiveFileInfo.setChecksum(fileDocument.getChecksum());
            archiveFileInfo.setGroupDocId(clientDirDoc.getDocId());
            archiveFileInfo.setFileSourceType("1");
            archiveFileInfo.setFileSourceId(null);
            archiveFileInfo.setCreateOperator(opUser.getUserid());
            archiveFileInfo.setCreateOperatorName(opUser.getName());
            archiveFileInfo.setDocId(dto.getFileDocId());
            archiveFileInfo.setDeleteFlag(0);
            archiveFileInfo = fileInfoRepository.save(archiveFileInfo);
            fileDocument.setDocType("1");
            documentService.save(fileDocument);
        }

        //建立file doc关联
        archiveDocument.setFileId(archiveFileInfo.getFileId());
        archiveDocumentRepository.save(archiveDocument);

        //关联目录
        if (Objects.isNull(clientDirDoc.getClientDirId())) {
            clientDirDoc.setClientDirId(dto.getClientDirId());
            clientDirDocRepository.save(clientDirDoc);
            //将待办任务自动完成
            if (Objects.isNull(clientDirDoc.getClientDirId())) {
                applicationContext.publishEvent(TaskInfoEvent.create("档案文件待匹配" + archiveFileInfo.getFileName(), dto.getClientId() + "", TaskTypeUrlEnum.ARCHIVE, "1"));
            }
        }
    }

    /**
     * 根据客户id更新客户信息
     *
     * @param client
     * @return
     */
    public ArchiveClient updateArchiveClientById(ArchiveClient client) {
        return clientRepository.save(client);
    }

    /**
     * 根据客户id信息创建客户目录实例信息
     *
     * @param clientId       客户id
     * @param opOperator     操作人id
     * @param opOperatorName 操作人姓名
     * @return
     */
    @Transactional
    public List<ArchiveDirClient> createByClientType(String clientId, String opOperator, String opOperatorName) {
        //1查询客户信息
        ArchiveClient client = findClientById(clientId);
        Assert.notNull(client, "创建客户目录实例信息失败-未查询到客户信息");
        //2根据客户类型查询档案目录模板
        List<ArchiveDirTemplate> archiveDirTemplates = findArchiveDirTemplateByClientType(client.getClientType());
        //3创建客户目录实例
        List<ArchiveDirClient> res = Lists.newArrayList();

        for (ArchiveDirTemplate template : archiveDirTemplates) {
            ArchiveDirClient archiveDirClient = ArchiveDirClient.builder().clientDirName(template.getDirTemplateName())
                    .clientId(clientId).clientParentDirId(null).dirTemplateId(template.getDirTemplateId())
                    .createTime(LocalDateTime.now()).saveFileFlag(template.getSaveFileFlag()).build();
            res.add(archiveDirClient);
        }
        //保存生成id
        res = dirClientRepository.saveAll(res);

        //4构建目录上下级关联关系
        Map<Integer, ArchiveDirClient> templateArchiveDirClientMap = res.stream().collect(Collectors.toMap(ArchiveDirClient::getDirTemplateId, e -> e, (i, j) -> i));
        Map<Integer, ArchiveDirTemplate> idArchiveDirTemplateMap = archiveDirTemplates.stream().collect(Collectors.toMap(ArchiveDirTemplate::getDirTemplateId, e -> e, (i, j) -> i));
        for (ArchiveDirClient dirClient : res) {
            ArchiveDirTemplate archiveDirTemplate = idArchiveDirTemplateMap.get(dirClient.getDirTemplateId());
            if (Objects.isNull(archiveDirTemplate.getParentDirTemplateId())) {
                dirClient.setClientParentDirId(null);
            } else {
                ArchiveDirClient parentArchiveDirClient = templateArchiveDirClientMap.get(archiveDirTemplate.getParentDirTemplateId());
                dirClient.setClientParentDirId(parentArchiveDirClient.getClientDirId());
            }
        }
        //保存关联关系
        res = dirClientRepository.saveAll(res);
        return res;
    }

    /**
     * 根据客户类型查询档案目录模板信息
     *
     * @param clientType
     * @return
     */
    public List<ArchiveDirTemplate> findArchiveDirTemplateByClientType(String clientType) {
        if (StringUtils.isBlank(clientType)) {
            return null;
        }
        return dirTemplateRepository.findAll(Example.of(ArchiveDirTemplate.builder().dirTemplateType(clientType).build()));
    }

    /**
     * 条件查询档案信息
     *
     * @param param
     * @return
     */
    public List<ArchiveDocument> findDocumentByCondition(Map<String, Object> param) {
        return archiveDocumentRepository.findAll(SpecificationUtil.buildSpecification(param, ArchiveDocument.class));
    }

    /**
     * 条件查询文件信息
     *
     * @param param
     * @return
     */
    public List<ArchiveFileInfo> findFileByCondition(Map<String, Object> param) {
        List list = new ArrayList();
        list.add(0);
        list.add(2);
        param.put("IN_deleteFlag", StringUtils.join(list, ","));
        return fileInfoRepository.findAll(SpecificationUtil.buildSpecification(param, ArchiveFileInfo.class));
    }

    /**
     * 保存客户信息
     *
     * @param archiveClient
     * @return
     */
    public ArchiveClient saveArchiveClient(ArchiveClient archiveClient) {
        return clientRepository.save(archiveClient);
    }

    /**
     * 自动下载【08.交易运营事项用印审批OA流程】文件-股票衍生品用
     *
     * @param requestId
     */
    @Transactional
    public void autoDownLoadOperateMattersOaFile(String requestId) {
        log.info("自动下载【08.交易运营事项用印审批OA流程】文件-股票衍生品用-被触发requestId={requestId}");
        List<OaFileDto> operateMattersOaFileList = gatewayFeignService.getOperateMattersOaFile(requestId);
        if (CollectionUtils.isEmpty(operateMattersOaFileList)) {
            log.info("未查询到requestId={}的08.交易运营事项用印审批OA流程有文件信息", requestId);
            return;
        }
        List<OaFileDto> files = gatewayFeignService.getFileStreamByFileId(operateMattersOaFileList);
        if (CollectionUtils.isEmpty(files)) {
            return;
        }

        //查询客户目录，并将文件关系保存到指定目录
        String clientId = operateMattersOaFileList.get(0).getCustId();
        if (StringUtils.isBlank(clientId)) {
            log.info("未查询到requestId={}的08.交易运营事项用印审批OA流程有客户信息", requestId);
            return;
        }
        List<ArchiveDirClient> dirClients = findArchiveDirClientByClientId(clientId);

        for (OaFileDto file : files) {
            try {
                ArchiveDirClient dirClient = null;
                ArchiveClientDirDoc clientDirDoc = null;
                String fileName = file.getFileName().substring(0, file.getFileName().lastIndexOf("."));

                String archiveName = ArchiveEnum.findArchiveNameByFileName(fileName);
                if (StringUtils.isBlank(archiveName)) {
                    archiveName = fileName;
                }
                List<ArchiveDirClient> thisFileDir = new ArrayList<>();
                for (ArchiveDirClient e : dirClients) {
                    if (e.getClientDirName().equals(archiveName)) {
                        thisFileDir.add(e);
                        break;
                    }
                }
                if (CollectionUtils.isEmpty(thisFileDir)) {
                    //文件属于未关联文档的文件
                    clientDirDoc = new ArchiveClientDirDoc();
                } else {
                    dirClient = thisFileDir.get(0);
                    List<ArchiveClientDirDoc> clientDirDocList = clientDirDocRepository.findAll(Example.of(ArchiveClientDirDoc.builder().clientId(clientId).clientDirId(dirClient.getClientDirId()).build()));
                    if (CollectionUtils.isEmpty(clientDirDocList)) {
                        clientDirDoc = new ArchiveClientDirDoc();
                        clientDirDoc.setClientDirId(dirClient.getClientDirId());
                    } else {
                        clientDirDoc = clientDirDocList.get(0);
                    }
                }

                if (Objects.isNull(clientDirDoc.getDocId())) {
                    if (Objects.nonNull(clientDirDoc)) {
                        clientDirDoc.setClientDirId(clientDirDoc.getClientDirId());
                    }
                    clientDirDoc.setClientId(clientId);
                    clientDirDocRepository.save(clientDirDoc);
                }

                PlatformResponse platformResponse = documentService.uploadFile(file.getFile());
                Map<String, Object> uploadFile = (Map<String, Object>) platformResponse.getData();
                if (Objects.isNull(uploadFile)) {
                    return;
                }

                ArchiveFileInfo archiveFileInfo = new ArchiveFileInfo();
                archiveFileInfo.setFileName((String) uploadFile.get("fileName"));
                archiveFileInfo.setFilePath((String) uploadFile.get("filePath"));
                archiveFileInfo.setChecksum((String) uploadFile.get("checksum"));
                archiveFileInfo.setGroupDocId(clientDirDoc.getDocId());
                archiveFileInfo.setFileSourceType("2");
                archiveFileInfo.setFileSourceId(requestId);
                archiveFileInfo.setDeleteFlag(0);
                archiveFileInfo.setDocId((Integer) uploadFile.get("id"));
                archiveFileInfo = fileInfoRepository.save(archiveFileInfo);

                ArchiveDocument document = new ArchiveDocument();
                document.setDocId(clientDirDoc.getDocId());
                document.setFileId(archiveFileInfo.getFileId());
                archiveDocumentRepository.save(document);

                //未匹配到目录信息，则生成待办任务
                if (Objects.isNull(clientDirDoc.getClientDirId())) {
                    applicationContext.publishEvent(TaskInfoEvent.create("档案文件待匹配" + archiveFileInfo.getFileName(), clientId + "", TaskTypeUrlEnum.ARCHIVE, "0"));
                }

            } catch (IOException e) {
                e.printStackTrace();
                log.error("自动下载【08.交易运营事项用印审批OA流程】文件-股票衍生品用异常", e);
            }
        }
    }

    /**
     * 根据客户id查询所有未关联的文件
     *
     * @param clientId
     * @return
     */
    public List<ArchiveClientDirDoc> listNoConnectFileByClientId(String clientId) {
        if (Objects.isNull(clientId)) {
            return Lists.newArrayList();
        }

        List<ArchiveClientDirDoc> clientDirDocList = clientDirDocRepository.findAll(Example.of(ArchiveClientDirDoc.builder()
                .clientId(clientId).build()));
        if (CollectionUtils.isEmpty(clientDirDocList)) {
            return Lists.newArrayList();
        }
        List<ArchiveClientDirDoc> dirDocList = clientDirDocList.stream().filter(e -> Objects.isNull(e.getClientDirId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(dirDocList)) {
            return Lists.newArrayList();
        }

        return dirDocList;
    }


    /**
     * 根据文件id手动删除文件
     *
     * @param fileId
     */
    public void deleteArchiveFile(Integer fileId) {
        Optional<ArchiveFileInfo> fileInfoOptional = fileInfoRepository.findById(fileId);

        Assert.isTrue(fileInfoOptional.isPresent(), "数据查询异常,不可删除");

        ArchiveFileInfo archiveFileInfo = fileInfoOptional.get();
        Optional<ArchiveDocument> documentOptional = archiveDocumentRepository.findById(archiveFileInfo.getGroupDocId());
        if (documentOptional.isPresent()) {
            ArchiveDocument document = documentOptional.get();
            document.setFileId(null);

            archiveDocumentRepository.deleteById(document.getDocId());

        }

        //Assert.isTrue(Objects.nonNull(document.getFileId()), "数据逻辑关联缺失,不可删除");
        archiveFileInfo.setDeleteFlag(1);
        fileInfoRepository.save(archiveFileInfo);
    }

    /**
     * 文件归档
     *
     * @param fileId
     */
    public void archivist(Integer fileId) {
        Optional<ArchiveFileInfo> fileInfoOptional = fileInfoRepository.findById(fileId);
        Assert.isTrue(fileInfoOptional.isPresent(), "未查询到该文件");
        ArchiveFileInfo archiveFileInfo = fileInfoOptional.get();

        archiveFileInfo.setDeleteFlag(2);
        fileInfoRepository.save(archiveFileInfo);
    }

}
